package com.soul.server.server;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soul.autoconfig.template.SmsTemplate;
import com.soul.commons.exception.SoulGlobalException;
import com.soul.dubbo.api.db.*;
import com.soul.model.db.*;
import com.soul.model.vo.ErrorResult;
import com.soul.model.vo.PageResult;
import com.soul.model.vo.SettingsVo;
import com.soul.server.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@Service
public class SettingsService {

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private QuestionsApi questionsApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    /**
     *  用户通用设置 - 读取
     * @return
     */
    public SettingsVo findByUserSettings() {
        User user = UserHolder.getUser();
        Settings settings = settingsApi.findByUserSettings(user.getId());
        SettingsVo settingsVo = new SettingsVo();
        if (settings != null){
            BeanUtils.copyProperties(settings,settingsVo);
        }
        settingsVo.setPhone(user.getMobile());
        return settingsVo;
    }

    /**
     *  设置陌生人问题 - 保存
     * @return
     */
    public void UpdateUserQuestions(String content) {
        Question question = new Question();
        question.setUserId(UserHolder.getUser().getId());
        question.setTxt(content);
        questionsApi.UpdateUserQuestions(question);
    }

    /**
     *  通知设置 - 保存(更新)
     * @return
     */
    public void notificationsSetting(Settings settings) {
        settings.setUserId(UserHolder.getUserId());
        settingsApi.notificationsSetting(settings);
    }

    /**
     *  黑名单 - 翻页列表
     * @param page 页码
     * @param pagesize 当前页条数
     */
    public PageResult findBlacklist(Long page, Long pagesize) {

        User user = UserHolder.getUser();

        // 用户id查询被拉入黑名单用户信息
        PageResult<BlackList> blackListIds =  blackListApi.findBlacklistBatchIds(user.getId(),page, pagesize);
        List<BlackList> items = blackListIds.getItems();
        if (CollectionUtils.isEmpty(blackListIds.getItems())){
//            return new PageResult();
            return null;
        }
        List<Long> blackUserIds = items.stream().map(BlackList::getBlackUserId).collect(Collectors.toList());

        // 批量查询黑名单用户
        List<UserInfo> userInfoList = userInfoApi.findByIdsUserInfoList(blackUserIds);
        if (CollectionUtils.isEmpty(userInfoList)){
            return null;
        }

        return new PageResult(page,pagesize,blackListIds.getCounts(),userInfoList);
    }

    /**
     *  黑名单 - 移除
     * @param uid 黑名单用户id
     * @return
     */
    public void deleteBlackByUid(Long uid) {
        BlackList blackList = new BlackList();
        blackList.setUserId(UserHolder.getUserId());
        blackList.setBlackUserId(uid);
        blackListApi.deleteBlackByUid(blackList);
    }

    /**
     *  更新手机号码获取验证码
     */
    public void sendVerificationCode() {
        User user = UserHolder.getUser();
//        String code = RandomStringUtils.randomNumeric(6); // 获取随意验证码
        String code = "666666";
        if (false) smsTemplate.sendSms(user.getMobile(),code);
        // code验证码存储redis中
        redisTemplate.boundValueOps("VALIDATE_CODE_" + user.getMobile()).set(code);
    }

    /**
     *  更新手机号码校验验证码
     */
    public Map checkVerificationCode(String verificationCode) {
        Boolean verification = true;
        String codeKey = "VALIDATE_CODE_" + UserHolder.getUser().getMobile();
        // 从redis验证码比较是否一致
        String oldCode = redisTemplate.opsForValue().get("VALIDATE_CODE_" + UserHolder.getUser().getMobile());
        if (StringUtils.isEmpty(oldCode)) throw new SoulGlobalException(ErrorResult.loginError());
        if (!oldCode.equals(verificationCode)) throw new SoulGlobalException(ErrorResult.validateCodeError());
        redisTemplate.delete(codeKey);
        Map<String, Boolean> map = new HashMap<>();
        map.put("verification",verification);
        return map;
    }

    /**
     *  更新手机号码
     */
    public void updatePhone(String phone) {
        User user = UserHolder.getUser();
        user.setMobile(phone);
        userApi.updateById(user);
    }
}
